package com.zhz.lib.cms.manage.newscenter.action;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.lib.cms.domain.newscenter.News;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.lib.cms.utils.zhz.ZhzSecurityUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.zhzutil.ZhzDateUtil;

public class NewsAction extends DispatchAction {

	private BaseDAO baseDao;
	// 每页显示的记录数
	private Integer pageSize;
	// 事务模板
	private TransactionTemplate transactionTemplate;

	// 不给参数，默认执行此处
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return newslist(mapping, form, request, response);
	}

	/**
	 * 显示最新消息列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward newslist(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 取出选择的最新消息类型
		String radiooption = ZhzHttpRequestUtil.getParameters(request,
				"radiooption");

		// 获取搜索框的类型
		String keywordType = ZhzHttpRequestUtil.getParameters(request,
				"keywordType");
		// 获取搜索框的值
		String keyword = ZhzHttpRequestUtil.getParameters(request, "keyword");
		String keywordOut = null;
		if (StringUtil.isNotBlank(keyword)) {
			keyword = URLDecoder.decode(keyword);
			keywordOut = URLEncoder.encode(URLEncoder.encode(keyword));
		}
		// ///////////////////////////////////////
		// 获取页值
		int pageNow = 0;
		String pageNowString = ZhzHttpRequestUtil.getParameters(request,
				"pageNow");

		if (ZhzStringUtil.isNotNull(pageNowString)) {
			pageNow = Integer.parseInt(pageNowString.trim());
		} else {
			pageNow = 1;
		}
		if (pageNow <= 1)
			pageNow = 1;
		// ///////////////////////////////////////

		// ///////////////////////////////////////
		// 构造查询条件，获得查询结果的数量
		int entryTatal = 0;
		String whereStatement = null;

		// 根据搜索框的值进行查询
		if (StringUtil.equalsIgnoreCase(keywordType, "title")
				|| StringUtil.equalsIgnoreCase(keywordType, "writer")) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM News where ifDelete =0 and "
							+ keywordType + " like '%" + keyword + "%'");
			whereStatement = "where ifDelete =0 and " + keywordType
					+ " like '%" + keyword + "%'";
		} else {
			entryTatal = baseDao.getNumOnQuery(" FROM News where ifDelete =0");
			whereStatement = "where ifDelete =0";
		}
		// 根据选择的最新消息列表选项进行查询
		if (StringUtil.equals(radiooption, "weishenhe")) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM News where ifDelete =0 and  aproveState=0");
			whereStatement = "where ifDelete =0 and  aproveState=" + 0;
		} else if (StringUtil.equals(radiooption, "yitongguo")) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM News where ifDelete =0 and  aproveState=1");
			whereStatement = "where ifDelete =0 and  aproveState=" + 1;
		} else if (StringUtil.equals(radiooption, "weitongguo")) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM News where ifDelete =0 and  aproveState=2");
			whereStatement = "where ifDelete =0 and  aproveState=" + 2;
		} else if (StringUtil.equals(radiooption, "zhiding")) {
			entryTatal = baseDao
					.getNumOnQuery(" FROM News where ifDelete =0 and  top=1");
			whereStatement = "where ifDelete =0 and  top=" + 1;
		}

		int pageTatal = 0;
		if (entryTatal / pageSize == 0)
			pageTatal = entryTatal / pageSize + 1;
		else
			pageTatal = entryTatal / pageSize;
		if (pageNow > pageTatal) {
			pageNow = pageTatal;
		}

		// 根据当前页等条件查询
		List<News> newslist = baseDao.findAllByPage("News", whereStatement,
				"order by newsId DESC", pageNow, pageSize);

		// 查询的结果集
		request.setAttribute("newslist", newslist);

		request.setAttribute("pageNow", pageNow);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("pageTatal", pageTatal);
		request.setAttribute("entryTatal", entryTatal);
		request.setAttribute("keyword", keywordOut);
		request.setAttribute("keywordType", keywordType);
		request.setAttribute("radiooption", radiooption);

		return mapping.findForward("news-list");
	}

	/**
	 * 添加最新消息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward newsadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());

		return mapping.findForward("news-add");

	}

	/**
	 * 提交最新消息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward newssave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 获取最新消息的标题
		String title = ZhzHttpRequestUtil.getParameters(request, "title");
		// 获取最新消息的主内容
		String newscontent = ZhzHttpRequestUtil.getParameters(request,
				"newscontent");

		News news = new News();

		news.setTitle(title);
		news.setContent(newscontent);
		news.setWriter(ZhzSecurityUtil.getOperatorName());
		news.setKeyword(null);
		news.setPubDate(ZhzDateUtil.getYYYYMDDDate(request
				.getParameter("pubdate")));
		if (ZhzStringUtil.isNotNull(request.getParameter("iftop"))) {
			news.setTop(1);
			news.setTopStartTime(ZhzDateUtil.getYYYYMDDDate(request
					.getParameter("startdate")));
			news.setTopEndTime(ZhzDateUtil.getYYYYMDDDate(request
					.getParameter("enddate")));
		} else {
			news.setTop(0);
			news.setTopStartTime(null);
			news.setTopEndTime(null);
		}
		news.setHit(0);
		news.setAproveState(0);
		news.setAproveTime(null);
		news.setEditor(ZhzSecurityUtil.getOperatorName());
		news.setEditorTime(new Date());
		news.setIfDelete(0);

		request.setAttribute("add", true);

		boolean x = baseDao.save(news);

		if (x) {
			request.setAttribute("add", "add");
			request.setAttribute("addresult", "addresult");
		}

		return mapping.findForward("news-result");
	}

	/**
	 * 编辑最新消息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward newsedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");
		// 获取信息最新消息
		News news = (News) baseDao.findOneObject("News", "newsId", newsid);
		request.setAttribute("news", news);

		if (news.getTop() == 1)
			request.setAttribute("top", true);
		else
			request.setAttribute("top", false);

		return mapping.findForward("newsedit-form");
	}

	/**
	 * 编辑最新消息提交
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward newseditsave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");

		// 获取最新消息的标题
		String title = ZhzHttpRequestUtil.getParameters(request, "title");
		// 获取最新消息的主内容
		String newscontent = ZhzHttpRequestUtil.getParameters(request,
				"newscontent");

		News news = (News) baseDao.findOneObject("News", "newsId", newsid);

		news.setTitle(title);
		news.setContent(newscontent);
		news.setPubDate(ZhzDateUtil.getYYYYMDDDate(request
				.getParameter("pubdate")));
		if (ZhzStringUtil.isNotNull(request.getParameter("iftop"))) {
			news.setTop(1);
			news.setTopStartTime(ZhzDateUtil.getYYYYMDDDate(request
					.getParameter("startdate")));
			news.setTopEndTime(ZhzDateUtil.getYYYYMDDDate(request
					.getParameter("enddate")));
		} else {
			news.setTop(0);
			news.setTopStartTime(null);
			news.setTopEndTime(null);
		}
		news.setEditor(ZhzSecurityUtil.getOperatorName());
		news.setEditorTime(new Date());

		request.setAttribute("edit", true);
		boolean x = baseDao.update(news);

		if (x) {
			request.setAttribute("edit", "edit");
			request.setAttribute("editresult", "editresult");
		}

		return mapping.findForward("news-result");
	}

	/**
	 * 删除最新消息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward newsdel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		boolean delResult = false;

		String newsidString = ZhzHttpRequestUtil.getParameters(request,
				"newsid");

		if (ZhzStringUtil.isNotNull(newsidString)) {
			News news = (News) baseDao.findOneObject("News", "newsId",
					newsidString);
			// 设为删除
			news.setIfDelete(1);
			news.setEditor(ZhzSecurityUtil.getOperatorName());
			news.setEditorTime(new Date());

			delResult = baseDao.update(news);
		}
		if (delResult) {
			request.setAttribute("del", "del");
			request.setAttribute("delResult", "delResult");
		}
		return mapping.findForward("news-result");
	}

	/**
	 * 通过ajax请求，获取最新消息列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward newsContent(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");
		if (ZhzStringUtil.isNotNull(newsid)) {
			News news = (News) baseDao.findOneObject("News", "newsId", newsid);
			request.setAttribute("news", news);
		} else {
			return null;
		}
		return mapping.findForward("news-content");
	}

	/**
	 * 审核最新消息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward newsApprove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获取所有的参数
		Enumeration allParameter = request.getParameterNames();

		// 0 未审核 1 通过 2 不通过
		String aproveState = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
				.getParameter("approveState"));

		final int apoveStateInt = Integer.parseInt(aproveState);

		// 获取选择的所有待审核的模块
		final Set<String> newsIdSet = new HashSet<String>();

		String name = null;
		while (allParameter.hasMoreElements()) {
			name = (String) allParameter.nextElement();
			if (ZhzStringUtil.isNotNull(name)
					&& StringUtil.contains(name, "checkbox")) {
				// 将含有值的checkbox，赋值
				newsIdSet.add(request.getParameter(name));
			}
		}

		// 在事务中进行
		boolean approveResult = (Boolean) transactionTemplate
				.execute(new TransactionCallback() {

					public Object doInTransaction(TransactionStatus status) {

						try {
							Iterator it = newsIdSet.iterator();
							while (it.hasNext()) {
								String newsId = (String) it.next();
								News news = (News) baseDao.findOneObject(
										"News", "newsId", newsId);
								news.setAproveState(apoveStateInt);
								news.setAproveTime(Calendar.getInstance()
										.getTime());
								news.setEditor(ZhzSecurityUtil
										.getOperatorName());
								news.setEditorTime(new Date());

								baseDao.update(news);
							}
						} catch (Exception e) {
							status.setRollbackOnly();
							return false;
						}
						return true;
					}
				});

		if (approveResult) {
			request.setAttribute("app", "app");
			request.setAttribute("approveResult", "approveResult");
		}
		return mapping.findForward("news-result");
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public void setBaseDao(BaseDAO baseDao) {
		this.baseDao = baseDao;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

}